package com.opesoft.pf.jpa;

import java.util.HashMap;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.apache.log4j.Logger;

public class SessionManager
{
	static public Logger log=Logger.getLogger(SessionManager.class);

	static EntityManagerFactory entityManagerFactory;
	static String dataSourceName="hibernate"; // 数据源的名字，将来这里可能要考虑到不同的数据源！

	static Map<Thread, EntityManagerWrapper> activeSessions=new HashMap<Thread, EntityManagerWrapper>();

	static
	{
		init();
	}

	static void init()
	{
		try
		{
			entityManagerFactory=Persistence.createEntityManagerFactory(dataSourceName);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 创建一个当前线程的HibernateSession
	 */
	static private void create()
	{
		Thread thread=Thread.currentThread();

		if(activeSessions.get(thread)==null)
		{
			// 如果没有Factory的话，初始化一个
			if(entityManagerFactory==null&&!entityManagerFactory.isOpen()) init();

			EntityManager em=entityManagerFactory.createEntityManager();

			// TODO : 这个地方要加一个对异常的处理，因为可能无法正确得到EntityManager

			EntityManagerWrapper emw=new EntityManagerWrapper(em);
			activeSessions.put(thread,emw);

			log.debug("Create new session : "+em.hashCode());
		}
	}

	static public EntityManager open()
	{
		Thread thread=Thread.currentThread();

		EntityManagerWrapper hs=activeSessions.get(thread);
		if(hs==null)
		{
			create();
			hs=activeSessions.get(thread);
		}

		hs.beginTransaction();
		return hs.getEntityManager();
	}

	/**
	 * 结束Session的Transaction
	 * 
	 * @param submit
	 *            是否提交，为False的时候回滚
	 */
	static public void commit(boolean submit)
	{
		Thread thread=Thread.currentThread();
		EntityManagerWrapper hs=activeSessions.get(thread);

		hs.commitTransaction(submit);
	}

	/**
	 * 提交Session的Transaction
	 */
	static public void commit()
	{
		Thread thread=Thread.currentThread();
		EntityManagerWrapper hs=activeSessions.get(thread);

		hs.commitTransaction(true);
	}

	/**
	 * 回滚Session的Transaction
	 */
	static public void rollback()
	{
		Thread thread=Thread.currentThread();
		EntityManagerWrapper hs=activeSessions.get(thread);

		hs.commitTransaction(false);
	}

	static private void close(EntityManagerWrapper emw,Thread thread)
	{
		if(emw!=null)
		{
			EntityManager em=emw.getEntityManager();
			if(em.isOpen()) em.close();

			activeSessions.remove(thread);

			log.debug("Close the session : "+em.hashCode());
		}
	}

	static public void close()
	{
		Thread thread=Thread.currentThread();
		EntityManagerWrapper emw=activeSessions.get(thread);

		if(emw!=null&&emw.transaction!=null)
		{
			// 如果没有提交事务，就先提交一下事务，当然，为了保险起见，是rollback方式提交
			if(emw.transaction.isActive())
			{
				emw.transaction.rollback();
				log.debug("Rollback Transacton : "+emw.transaction.hashCode());
			}
		}

		close(emw,thread);
	}

	/**
	 * 返回当前活动的Session的数量
	 * 
	 * @return
	 */
	static public int getActiveSessionCount()
	{
		return activeSessions.size();
	}

}